package com.core.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.core.system.dao.SystemUserMapper;
import com.core.system.dao.SystemUserRoleMapper;
import com.core.system.service.IImMessageRecordService;
import com.core.system.service.ISystemUserService;
import com.core.system.utils.ConvertUtils;
import com.core.system.utils.SecurityUser;
import com.mysql.cj.util.StringUtils;
import com.pojo.dto.PageDto;
import com.pojo.dto.SystemUserDto;
import com.pojo.entity.SystemUserEntity;
import com.pojo.entity.SystemUserRoleEntity;
import com.pojo.req.im.ImRecordResp;
import com.pojo.req.user.UserInsertReq;
import com.pojo.resp.user.UserImRecordResp;
import com.pojo.resp.user.UserPageResp;
import com.utility.constant.Constant;
import com.utility.exception.ServiceException;
import com.utility.util.IdCreateBy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 系统用户表 服务实现类
 * </p>
 *
 * @author hewei
 * @since 2020-11-26
 */
@Service
public class SystemUserServiceImpl extends ServiceImpl<SystemUserMapper, SystemUserEntity> implements ISystemUserService {
    @Autowired
    private ISystemUserService iSystemUserService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private SystemUserRoleMapper systemUserRoleMapper;

//    @Autowired
//    private ConsumerTokenServices consumerTokenServices;

    @Autowired
    private SystemUserMapper systemUserMapper;

//    @Autowired
//    private RedisUtil redisUtil;

    @Autowired
    private IImMessageRecordService iImMessageRecordService;


    /**
     * 根据用户名获取用户信息
     * @param userName 用户名
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SystemUserEntity getUser(String userName) {
        QueryWrapper<SystemUserEntity> userEntity = new QueryWrapper<>();
        userEntity.eq("user_name",userName);
        List<SystemUserEntity> systemUserEntities = iSystemUserService.getBaseMapper().selectList(userEntity);
        if (!systemUserEntities.isEmpty()){
            return systemUserEntities.get(0);
        }
        return null;
    }

    @Override
    public String getUserName(Long userId) {
        LambdaQueryWrapper<SystemUserEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(SystemUserEntity::getUserName);
        List<SystemUserEntity> systemUserEntities = this.baseMapper.selectList(lambdaQueryWrapper);
        if (!systemUserEntities.isEmpty()){
            return systemUserEntities.get(0).getUserName();
        }
        return null;
    }

    @Override
    public Page<UserImRecordResp> selectOnlineUserList(PageDto pageDto) {
        IPage<SystemUserDto> userPage = new Page(pageDto.getPageNum(), pageDto.getPageSize());
        Page<UserImRecordResp> systemUserDtoPage = systemUserMapper.selectUserOnLinePage(userPage, SecurityUser.getUserId());
        systemUserDtoPage.getRecords().forEach(user ->{
            List<ImRecordResp> list = iImMessageRecordService.list(user.getId(), 1);
            if (!list.isEmpty()){
                ImRecordResp imRecordResp = list.get(0);
                user.setBody(imRecordResp.getBody());
                user.setRequestDate(imRecordResp.getRequestDate());
                user.setIsSelf(Constant.ZERO);
                if (SecurityUser.getUserId().equals(imRecordResp.getRequestId())){
                    user.setIsSelf(Constant.ONE);
                }
                user.setIsRead(imRecordResp.getIsRead());
            }
        });
        return systemUserDtoPage;
    }


    /**
     *查询用户列表
     *  根据参数多条件查询
     * @param pageDto
     * @return
     */
    @Override
    public IPage<UserPageResp> selectUserListPage(PageDto pageDto) {
        IPage<UserPageResp> userPage = new Page(pageDto.getPageNum(), pageDto.getPageSize());
        IPage<UserPageResp> systemUserDtos = systemUserMapper.selectUserListPage(userPage,pageDto);
        return systemUserDtos;
    }


    /**
     * 新增用户
     * @param userInsertReq
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUser(UserInsertReq userInsertReq) {
        addVerifyField( userInsertReq);
        SystemUserEntity systemUserEntity = ConvertUtils.Convert(userInsertReq, SystemUserEntity.class);
        /**
         *  新增用户
         */
        Long byId = IdCreateBy.getById();
        systemUserEntity.setId(byId);
        systemUserEntity.setIsEnable(Short.parseShort(Constant.ZERO));
        systemUserEntity.setOnLine(0);
        systemUserEntity.setPassword(bCryptPasswordEncoder.encode("123456"));
        systemUserMapper.insert(systemUserEntity);
        /**
         * 新增用户角色关联
         */
        SystemUserRoleEntity systemRoleEntity = new SystemUserRoleEntity();
        systemRoleEntity.setRoleId(userInsertReq.getRoleId());
        systemRoleEntity.setUserId(byId);
        return systemUserRoleMapper.insert(systemRoleEntity);
    }




    /**
     * 编辑用户
     * @param systemUserDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(SystemUserDto systemUserDto) {
        updateVerifyField( systemUserDto);

        /**
         *  编辑用户
         */
        if (null != systemUserDto.getPassword()){
            systemUserDto.setPassword(bCryptPasswordEncoder.encode(systemUserDto.getPassword()));
        }
        SystemUserEntity convert = ConvertUtils.Convert(systemUserDto, SystemUserEntity.class);
        systemUserMapper.updateById(convert);
        /**
         * 修改用户角色关联
         */
        LambdaQueryWrapper<SystemUserRoleEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemUserRoleEntity::getUserId,systemUserDto.getId());
        systemUserRoleMapper.delete(queryWrapper);
        SystemUserRoleEntity systemUserRoleEntity = new SystemUserRoleEntity();
        systemUserRoleEntity.setRoleId(systemUserDto.getRoleId());
        systemUserRoleEntity.setUserId(systemUserDto.getId());
        return systemUserRoleMapper.insert(systemUserRoleEntity);
    }




    /**
     * 删除用户
     * @param systemUserDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUser(SystemUserDto systemUserDto) {

        /**
         *  删除用户
         */
        systemUserDto.setIsDelete(Constant.ONE);
        systemUserMapper.updateById(ConvertUtils.Convert(systemUserDto, SystemUserEntity.class));
        /**
         * 删除用户角色关联
         */
        LambdaQueryWrapper<SystemUserRoleEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemUserRoleEntity::getUserId,systemUserDto.getId());
        systemUserRoleMapper.delete(queryWrapper);
//        return  removeToken(,getUserName(systemUserDto.getId())) ;
    }


    /**
     * 批量删除y用户
     * @param systemUserDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchDeleteUser(SystemUserDto systemUserDto) {
        if (StringUtils.isNullOrEmpty(systemUserDto.getIds())){
            throw new ServiceException("未选择删除的用户");
        }
        List<String> ids = Arrays.asList(systemUserDto.getIds().split(","));

        /**
         * 批量删除 用户角色关联表
         */
        LambdaQueryWrapper<SystemUserRoleEntity> roleEntityQueryWrapper = new LambdaQueryWrapper<>();
        roleEntityQueryWrapper.in(SystemUserRoleEntity::getUserId, ids);
        systemUserRoleMapper.delete(roleEntityQueryWrapper);
        /**
         * 批量删除用户
         */
        return systemUserMapper.deleteBatchIds(ids);
    }




    /**
     * 编辑用户状态
     * @param systemUserDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUserStatus(SystemUserDto systemUserDto) {

        /**
         *  编辑用户状态
         */
        SystemUserEntity systemUserEntity = systemUserMapper.selectById(systemUserDto.getId());
        if(null == systemUserEntity){
            throw new ServiceException("用户不存在");
        }
        short isEnable = systemUserEntity.getIsEnable();

        if (Short.compare(Short.parseShort(Constant.ZERO),isEnable)== 0){
            systemUserEntity.setIsEnable(Short.parseShort(Constant.ONE));
            systemUserMapper.updateById(systemUserEntity);
            /**
             *  用户被停用 清除
             */
//            BaseDto baseDto = getUserDto();
//            return removeToken(baseDto.getToken(),baseDto.getUserName()) ;
            return 1;
        }else {
            systemUserEntity.setIsEnable(Short.parseShort(Constant.ZERO));
            systemUserMapper.updateById(systemUserEntity);
            return 1;
        }
    }

    /**
     * 修改密码
     * @param systemUserDto
     * @return
     */
    @Override
    public int passwordUpdate(SystemUserDto systemUserDto){
        SystemUserEntity systemUserEntity = systemUserMapper.selectById(systemUserDto.getId());
        systemUserEntity.setPassword(bCryptPasswordEncoder.encode("123456"));
        return systemUserMapper.updateById(ConvertUtils.Convert(systemUserDto,SystemUserEntity.class));
    }

    @Override
    public SystemUserDto getUserDetails(Long id){
        return systemUserMapper.selectUserDetails(id);
    }

    @Override
    public SystemUserDto getCurrentDetails(){
        return systemUserMapper.selectUserDetails(SecurityUser.getUserId());
    }


    /**
     * 退出登录用户状态
     * @param accessToken  认证token
     * @param userName  用户名
     * @return
     */
    @Override
    public int removeToken(String accessToken, String userName) {
//        boolean boo = consumerTokenServices.revokeToken(accessToken);
//        if (boo) {
//            /**
//             *  清除redis存储的用户信息
//             */
//            if (redisUtil.hasKey(userName)) {
//                redisUtil.del(userName);
//            }
//        }
        return 1;
    }


    /**
     * 根据用户和菜单id 查询该用户该菜单的权限
     * @param templateId 菜单id
     * @return
     */
    public List<String> selectUserPermission(Long templateId){
        List<String> permission = baseMapper.selectUserPermission(SecurityUser.getUserId(), templateId);
        List<String> userPermissionList = new ArrayList<>();
        permission.forEach(l ->{
            userPermissionList.add(l.split(":")[1]);
        });
        return userPermissionList;
    }


    /**
     * 验证
     *      用户名
     *      手机号
     *      邮箱
     *      是否重复
     * @param userInsertReq
     */
    @Transactional(rollbackFor = Exception.class)
    public void addVerifyField(UserInsertReq userInsertReq){
        /**
         *  新增情况下
         *  验证唯一字段不能重复
         */
        if (null != getUser(userInsertReq.getUserName())){
            throw new ServiceException("用户名已存在");
        }
        if (null != userInsertReq.getPhone()){
            LambdaQueryWrapper<SystemUserEntity> userEntity = new LambdaQueryWrapper<>();
            userEntity.eq(SystemUserEntity::getPhone,userInsertReq.getPhone());
            if (!iSystemUserService.getBaseMapper().selectList(userEntity).isEmpty()){
                throw new ServiceException("手机号已存在");
            }
        }
        if (null != userInsertReq.getMail()){
            LambdaQueryWrapper<SystemUserEntity> userEntity = new LambdaQueryWrapper<>();
            userEntity.eq(SystemUserEntity::getMail,userInsertReq.getMail());
            if (!iSystemUserService.getBaseMapper().selectList(userEntity).isEmpty()){
                throw new ServiceException("邮箱已存在");
            }
        }
    }

    /**
     * 验证
     *      用户名
     *      手机号
     *      邮箱
     *      是否重复
     * @param systemUserDto
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateVerifyField(SystemUserDto systemUserDto){
        /**
         * 编辑情况下  如果编辑的自己则不需要判断 是否重复
         */
        SystemUserEntity systemUserEntity = iSystemUserService.getBaseMapper().selectById(systemUserDto.getId());
        if (null != systemUserEntity.getUserName() && !systemUserDto.getUserName().equals(systemUserEntity.getUserName())){
            throw new ServiceException("用户名已存在");
        }
        if (null != systemUserEntity.getPhone() && !systemUserDto.getPhone().equals(systemUserEntity.getPhone())){
            throw new ServiceException("手机号已存在");
        }
        if (null != systemUserEntity.getMail() && !systemUserDto.getMail().equals(systemUserEntity.getMail())){
            throw new ServiceException("邮箱已存在");
        }
    }


}
